package com.mcsyr.clearitem;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Objects;

import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.ItemSpawnEvent;

import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

public class Event implements Listener {

    @EventHandler
    public void onPlayerJoin(final PlayerJoinEvent event) {
        tools.initPlayerData(event.getPlayer());
    }

    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerDropItem(final PlayerDropItemEvent event) {
        Player player = event.getPlayer();
        if (Main.DropEnable) {
            if (Main.PlayerDropLock.get(player)) {
                event.setCancelled(true);
                event.getPlayer().sendMessage(Main.DropMessageDiscardInOpen);
            }
        }
    }

    @EventHandler
    public void onItemSpawn(final ItemSpawnEvent event) {
        List<Entity> Entities = event.getEntity().getNearbyEntities(16, 32, 16);
        if (Entities.size() >= Main.ClearItemChunkMaxItems) {
            List<String> lore = null;
            ItemMeta itemMeta = null;
            for (final Entity ent : Entities) {
                tools.clearEntityItem(ent, lore, itemMeta);
            }
            List<LivingEntity> worldEntities = event.getEntity().getWorld().getLivingEntities();
            Player player = null;
            for (final Entity entity : worldEntities) {
                if (entity instanceof Player) {
                    player = (Player) entity;
                    break;
                }
            }
            String message = Main.ClearItemMessageClearChunkMaxItems.replace("%world%", "%multiverse_world_alias%");
            message = PlaceholderAPI.setPlaceholders(player, message);
            DecimalFormat df = new DecimalFormat("0.0 ");
            message = message.replace("%X%", df.format(event.getLocation().getX()))
                    .replace("%Y%", df.format(event.getLocation().getY()))
                    .replace("%Z%", df.format(event.getLocation().getZ()));
            Bukkit.getServer().broadcastMessage(message);
        }
    }

    @EventHandler(priority = EventPriority.HIGHEST)
    public void onInventoryClick(final InventoryClickEvent event) {
        Player player = ((Player) event.getWhoClicked());
        final ItemStack itemStack = event.getCurrentItem();
        if (itemStack == null || "AIR".equals(itemStack.getType().name())) {
            return;
        }
        String Title = event.getView().getTitle();
        if (Title.startsWith(Main.PublicDustbinName)) {// 公共垃圾箱
            if (Main.DustbinLock) {
                player.sendMessage(Main.PublicDustbinName + "垃圾箱已被锁住，请稍等1秒后操作...");
                event.setCancelled(true);
                return;
            }
            if (itemStack.getItemMeta() == null) return;
            final String name = itemStack.getItemMeta().getDisplayName();
            if (name == null || name.length() == 0) return;
            if (name.contains(Main.PublicDustbinNextButtonName)) {
                event.setCancelled(true);
                int page = Integer.parseInt(Title.replace(Main.PublicDustbinName, ""));
                if (page < Main.PublicDustbinPageSize-1) {
                    player.openInventory(Dustbin.Dustbins.get(++page));
                }
            } else if (name.contains(Main.PublicDustbinPrevButtonName)) {
                event.setCancelled(true);
                int page = Integer.parseInt(Title.replace(Main.PublicDustbinName, ""));
                if (page > 0) {
                    player.openInventory(Dustbin.Dustbins.get(--page));
                }
            }
        } else if (Main.DropEnable && Title.equals(Main.PrivateDustbinName)) {// 私人垃圾箱
            final String name = Objects.requireNonNull(itemStack.getItemMeta()).getDisplayName();
            if (tools.isIncludedString(Main.PrivateDustbinWhiteListName, name)) {
                event.setCancelled(true);
            }
            if (itemStack.getItemMeta() == null) return;
            final List<String> lores = itemStack.getItemMeta().getLore();
            if (lores == null) return;
            for (String lore : lores) {
                if (tools.isIncludedString(Main.PrivateDustbinWhiteListLore, lore)) {
                    event.setCancelled(true);
                    return;
                }
            }
        }
    }

    @EventHandler
    public void onInventoryClose(final InventoryCloseEvent event) {
        Player player = (Player) event.getPlayer();
        if (Main.PrivateDustbinEnable) {
            if (event.getView().getTitle().equals(Main.PrivateDustbinName)) {
                Inventory inventory = Main.PlayerPrivateDustbin.get(player);
                ItemStack[] itemStacks = inventory.getContents();
                int clear = 0;
                int preserve = 0;
                for (ItemStack itemStack : itemStacks) {
                    if (itemStack == null) continue;
                    if (Dustbin.addItem(itemStack)) {
                        inventory.remove(itemStack);
                        clear++;
                    } else {
                        preserve++;
                    }
                }
                if (clear > 0 || preserve > 0) {
                    player.sendMessage(Main.PrivateDustbinMessageClear
                            .replaceAll("%clear%", String.valueOf(clear))
                            .replaceAll("%preserve%", String.valueOf(preserve))
                    );
                }
            }
        }
    }
}
